/*
 * @Date: 2023-02-23 16:56:10
 * @LastEditors: Zireael 1193875164@qq.com
 * @LastEditTime: 2023-03-26 15:00:01
 * @FilePath: \A19\frontend\src\hooks\wsCommunicate.ts
 */
import { ServiceType } from '@/shared/protocols/serviceProto';
import { WsClient } from 'tsrpc-browser';
import { reactive, ref, watch, Ref, nextTick } from 'vue';
import { users } from '../shared/types/user';
import { useClientStore } from '../pinia/stores/client';
import { gsap } from 'gsap'

export function wsCommunicate(wsClient:WsClient<ServiceType>,courseId:string,ul:Ref<HTMLUListElement | undefined>){
    const client = useClientStore().client
    const talking = ref('')
    const talks = reactive(new Array<{
        user:users
        talk:string
    }>())
    watch(talks,newValue =>{
        console.log(newValue);
    })

    wsClient.listenMsg('AMessages/Communicate/InitComm',msg =>{
        talks.push(...msg.talks)
        scrollDown()
    })
    wsClient.listenMsg('AMessages/Communicate/ReceiveTalk',msg =>{
        talks.push(msg.talk)
        scrollDown()
    })
    wsClient.listenMsg('AMessages/Live/SBTalk',msg =>{
        talking.value = msg.studentId
    })

    const sendTalk = async (talk:string)=>{
        return await client.callApi('AMessages/Live/Communicate',{
            courseId,
            talk,
            type:'talk'
        })
    }

    const talk = ref("");
    const newTalk = async () => {
    if(!talk.value){
        return ElMessage.warning('请输入内容')
    }
    const ret = await sendTalk(talk.value);
    if (ret.isSucc) {
        talk.value = "";
    }
    };

    const scrollDown = () =>{
        nextTick(() =>{
            if(!ul.value) return
            ul.value.scrollTo({
                top:ul.value.offsetHeight + ul.value.scrollHeight,
                behavior:'smooth'
            })
        })
    }

    return{
        talk,
        talks,
        sendTalk,
        newTalk,
        talking,
    }
}